<template>
  <div class="room-management">
    <!-- 上模块 -->
    <div class="top-section">
      <el-card shadow="hover">
        <div class="campus-header">
          <div class="left-panel">
            <el-avatar
                :size="160"
                shape="square"
                :data-campus="currentCampus?.id"
                class="campus-avatar"
            />
            <div class="campus-info">
              <div class="name-area">
                <h2 class="campus-name">{{ currentCampus?.name }}</h2>
                <el-select
                    v-model="selectedCampus"
                    placeholder="更换园区"
                    class="campus-switcher"
                    @change="updateCampusInfo"
                >
                  <el-option
                      v-for="campus in campuses"
                      :key="campus.park_id"
                      :label="campus.park_name || '未知园区'"
                      :value="campus.park_id"
                  />
                </el-select>
              </div>
              <div class="stats-grid">
                <div class="stat-item" v-for="(stat, index) in statsItems" :key="index">
                  <div class="stat-label">{{ stat.label }}</div>
                  <div class="stat-value">{{ stat.value }}</div>
                </div>
              </div>
            </div>
          </div>

          <el-button
              type="primary"
              icon="el-icon-office-building"
              @click="manageBuildings"
              class="manage-btn"
              size="medium"
          >
            楼宇信息
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 中模块 -->
    <div class="middle-section">
      <el-card shadow="hover" class="filter-card">
        <div class="filter-container">
          <div class="filter-row">
            <div class="filter-item">
              <span class="filter-label">厂房号：</span>
              <el-input
                  v-model="filters.roomNumber"
                  placeholder="输入厂房号搜索"
                  clearable
                  class="filter-input"
              />
            </div>

            <div class="filter-item">
              <span class="filter-label">面积：</span>
              <el-select
                  v-model="filters.areaRange"
                  multiple
                  collapse-tags
                  placeholder="请选择面积范围"
                  class="filter-select"
              >
                <el-option
                    v-for="item in areaOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </div>
          </div>

          <div class="filter-row">
            <div class="filter-item">
              <span class="filter-label">楼宇：</span>
              <el-select
                  v-model="filters.building"
                  multiple
                  collapse-tags
                  placeholder="请选择楼宇"
                  class="filter-select building-select"
              >
                <el-option
                    v-for="item in buildingOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 下模块 -->
    <div class="bottom-section">
      <el-card shadow="hover" class="table-card">
        <div class="table-header">
          <div class="header-left">
            <span class="summary-text">
              楼宇 {{ buildingCount }} | 厂房 {{ roomCount }}
            </span>
          </div>

          <div class="header-right">
            <el-button-group>
              <el-button type="primary" plain icon="el-icon-tickets" @click="manageFloors">楼层信息</el-button>
              <el-button type="primary" plain icon="el-icon-house" @click="manageRooms">厂房信息</el-button>
            </el-button-group>
          </div>
        </div>

        <el-table
            :data="filteredData"
            border
            style="width: 100%"
            class="data-table"
            v-loading="tableLoading"
        >
          <el-table-column prop="buildingName" label="楼宇" />
          <el-table-column prop="floorName" label="楼层" />
          <el-table-column label="厂房号">
            <template #default="{ row }">
              <el-link type="primary" @click="viewRoomDetail(row)">{{ row.roomNumber }}</el-link>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="类型" />
          <el-table-column prop="area" label="租赁面积(㎡)" />
          <el-table-column prop="rentBase" label="租金" />
          <el-table-column prop="propertyBase" label="物业费" />
          <el-table-column prop="status" label="状态" />
        </el-table>

        <!-- 分页控件 -->
        <div class="pagination-container">
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="pagination.currentPage"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="pagination.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="pagination.total"
          />
        </div>
      </el-card>
    </div>

    <!-- 楼宇管理对话框 -->
    <el-dialog
        title="楼宇信息"
        v-model="buildingDialogVisible"
        width="80%"
        top="5vh"
        @close="handleBuildingDialogClose"
        class="building-manage-dialog"
    >
      <el-table :data="buildingList" border style="width: 100%">
        <el-table-column prop="name" label="楼宇名称" width="120" />
        <el-table-column prop="buildingArea" label="建筑面积(㎡)" width="120" />
        <el-table-column prop="rentableArea" label="可租面积(㎡)" width="120" />
        <el-table-column prop="roomCount" label="房间数量" width="100" />
        <el-table-column prop="address" label="楼宇地址" min-width="200" />
        <el-table-column label="操作" width="150" align="center">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                  type="primary"
                  link
                  size="small"
                  @click="viewBuildingDetail(row)"
              >
                详情
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <div class="footer-buttons">
          <el-button @click="buildingDialogVisible = false">关 闭</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 楼宇详情对话框 -->
    <el-dialog
        title="楼宇详情"
        v-model="viewDialogVisible"
        width="700px"
        @close="resetBuildingForm"
    >
      <el-form
          :model="currentBuilding"
          ref="buildingFormRef"
          label-width="120px"
          :disabled="true"
      >
        <el-form-item label="所属园区" prop="park_id">
          <el-select
              v-model="currentBuilding.park_id"
              placeholder="请选择所属园区"
              style="width: 100%"
          >
            <el-option
                v-for="campus in campuses"
                :key="campus.park_id"
                :label="campus.park_name"
                :value="campus.park_id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="楼宇名称" prop="name">
          <el-input v-model="currentBuilding.name" placeholder="请输入楼宇名称" />
        </el-form-item>

        <el-form-item label="楼宇编号">
          <el-input v-model="currentBuilding.building_number" placeholder="请输入楼宇编号" />
        </el-form-item>

        <el-form-item label="地上楼层">
          <el-input-number
              v-model="currentBuilding.ground_floor_plan"
              :min="0"
              :max="100"
              controls-position="right"
              style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="地下楼层">
          <el-input-number
              v-model="currentBuilding.underground_floor_plan"
              :min="0"
              :max="10"
              controls-position="right"
              style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="楼宇地址" prop="address">
          <el-input
              v-model="currentBuilding.building_address"
              type="textarea"
              :rows="2"
              placeholder="请输入详细地址"
          />
        </el-form-item>

        <el-form-item label="产权性质" prop="property_region">
          <el-input
              v-model="propertyRegionText"
              :disabled="true"
              placeholder="产权性质"
          />
        </el-form-item>

        <el-form-item label="不动产编号">
          <el-input v-model="currentBuilding.real_estate_number" placeholder="请输入不动产编号" />
        </el-form-item>

        <el-form-item label="产权编号">
          <el-input v-model="currentBuilding.property_rights_number" placeholder="请输入产权编号" />
        </el-form-item>

        <el-form-item label="土地编号">
          <el-input v-model="currentBuilding.land_number" placeholder="请输入土地编号" />
        </el-form-item>

        <el-form-item label="建筑面积(㎡)" prop="buildingArea">
          <el-input-number
              v-model="currentBuilding.building_area"
              :min="100"
              :max="100000"
              controls-position="right"
              style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="产权面积(㎡)" prop="propertyArea">
          <el-input-number
              v-model="currentBuilding.property_area"
              :min="50"
              :max="currentBuilding.building_area"
              controls-position="right"
              style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="招商面积(㎡)">
          <el-input-number
              v-model="currentBuilding.rentable_space"
              :min="0"
              :max="currentBuilding.building_area"
              controls-position="right"
              style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="自用面积(㎡)">
          <el-input-number
              v-model="currentBuilding.self_used_area"
              :min="0"
              :max="currentBuilding.building_area"
              style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="楼宇图片">
          <el-upload
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-success="handleUploadSuccess"
              :file-list="fileList"
              :limit="1"
              accept=".jpg,.jpeg,.png"
          >
            <i class="el-icon-plus"></i>
            <template #tip>
              <div class="el-upload__tip">
                只能上传 jpg/png 文件，且不超过2MB
              </div>
            </template>
          </el-upload>
          <el-dialog v-model="dialogImageVisible" append-to-body class="picture-preview" >
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item>

        <el-form-item label="楼宇设施服务">
          <el-checkbox-group v-model="currentBuilding.building_features">
            <el-checkbox label="中央空调">中央空调</el-checkbox>
            <el-checkbox label="电梯">电梯</el-checkbox>
            <el-checkbox label="监控覆盖">监控覆盖</el-checkbox>
            <el-checkbox label="食堂">食堂</el-checkbox>
            <el-checkbox label="会议室">会议室</el-checkbox>
            <el-checkbox label="智能门禁">智能门禁</el-checkbox>
            <el-checkbox label="人脸识别">人脸识别</el-checkbox>
            <el-checkbox label="高速宽带">高速宽带</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="楼宇简介" prop="building_introduction">
          <el-input
              v-model="currentBuilding.building_introduction"
              type="textarea"
              :rows="4"
              placeholder="请输入楼宇简介"
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button
            type="primary"
            @click="viewDialogVisible = false"
        >
          关 闭
        </el-button>
      </div>
    </el-dialog>

    <!-- 房间详情对话框 -->
    <el-dialog
        title="厂房详情"
        v-model="roomDetailDialogVisible"
        width="50%"
        top="5vh"
        @close="currentRoom = null"
    >
      <el-descriptions
          v-if="currentRoom"
          :column="2"
          border
          size="medium"
      >
        <el-descriptions-item label="楼宇">{{ currentRoom.name }}</el-descriptions-item>
        <el-descriptions-item label="楼层">{{ currentRoom.floor }}</el-descriptions-item>
        <el-descriptions-item label="厂房号">{{ currentRoom.room_number }}</el-descriptions-item>
        <el-descriptions-item label="类型">{{ currentRoom.type }}</el-descriptions-item>
        <el-descriptions-item label="租赁面积">{{ currentRoom.area }}㎡</el-descriptions-item>
        <el-descriptions-item label="房源状态">{{ currentRoom.status }}</el-descriptions-item>
        <el-descriptions-item label="租金">{{ currentRoom.rent_price }}元/㎡·天</el-descriptions-item>
        <el-descriptions-item label="物业费">{{ currentRoom.property_price }}元/㎡·月</el-descriptions-item>
      </el-descriptions>
      <div v-else class="empty-tip">
        <el-empty description="未找到厂房信息" />
      </div>

      <template #footer>
        <el-button @click="roomDetailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 楼层管理对话框 -->
    <el-dialog
        title="楼层信息"
        v-model="floorDialogVisible"
        width="80%"
        top="5vh"
        @close="resetFloorForm"
    >
      <el-table :data="floorList" border style="width: 100%">
        <el-table-column prop="campusName" label="所属园区" />
        <el-table-column prop="buildingName" label="所属楼宇" />
        <el-table-column prop="floorName" label="楼层名称" />
        <el-table-column prop="floorCode" label="楼层编号" />
        <el-table-column prop="floorHeight" label="层高">
          <template #default="{ row }">
            {{ row.floorHeight }}米
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="floorDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 厂房信息对话框 -->
    <el-dialog
        title="厂房信息"
        v-model="roomManagementDialogVisible"
        width="80%"
        top="5vh"
        @close="resetRoomManagementForm"
    >
      <div class="filter-row">
        <div class="filter-item">
          <span class="filter-label">楼宇：</span>
          <el-select
              v-model="roomFilters.building"
              placeholder="请选择楼宇"
              class="filter-select"
              @change="filterRooms"
              clearable
          >
            <el-option
                v-for="building in currentCampusBuildings"
                :key="building.id"
                :label="building.name"
                :value="building.name"
            />
          </el-select>
        </div>
        <div class="filter-item">
          <span class="filter-label">楼层：</span>
          <el-select
              v-model="roomFilters.floor"
              placeholder="请选择楼层"
              class="filter-select"
              @change="filterRooms"
          >
            <el-option
                v-for="floor in getAvailableFloors(roomFilters.building)"
                :key="floor"
                :label="floor"
                :value="floor"
            />
          </el-select>
        </div>
      </div>

      <el-table
          :data="filteredRoomData"
          border
          style="width: 100%"
          class="data-table"
          v-loading="loadingRooms"
      >
        <el-table-column prop="roomNumber" label="厂房号" />
        <el-table-column prop="buildingName" label="所属楼宇" />
        <el-table-column prop="floorName" label="楼层" />
        <el-table-column prop="type" label="类型" />
        <el-table-column prop="area" label="租赁面积(㎡)" />
        <el-table-column prop="status" label="状态" />
        <el-table-column prop="rentBase" label="租金" />
        <el-table-column prop="propertyBase" label="物业费" />
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="roomManagementDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch ,nextTick} from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

// API基础URL（从环境变量读取，自动适配环境）
const API_BASE = import.meta.env.VITE_API_BASE_URL;

const buildingList = ref([])
// 响应式数据
const selectedCampus = ref(1)
const buildingDialogVisible = ref(false)
const roomDetailDialogVisible = ref(false)
const currentRoom = ref(null)
const viewDialogVisible = ref(false)
const dialogImageVisible = ref(false)
const dialogImageUrl = ref('')
const fileList = ref([])
const tableLoading = ref(false)
const loading = ref(false)
const loadingRooms = ref(false)
const viewMode = ref(false)
const propertyTypes = ref([])

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const campuses = ref([])

const filters = reactive({
  roomNumber: '',
  areaRange: [],
  building: []
})

const areaOptions = ref([
  { value: '0-100', label: '100㎡以下' },
  { value: '100-200', label: '100-200㎡' },
  { value: '200-300', label: '200-300㎡' },
  { value: '300-500', label: '300-500㎡' },
  { value: '500-1000', label: '500-1000㎡' },
  { value: '1000+', label: '1000㎡以上' }
])

const buildingOptions = ref([])

const tableData = ref([])

// 楼宇管理相关数据
const currentBuilding = reactive({
  id: null,
  park_id: selectedCampus.value, // 默认当前园区
  name: '',
  building_number: '',
  ground_floor_plan: 0,
  underground_floor_plan: 0,
  building_address: '',
  property_region: '',
  real_estate_number: '',
  property_rights_number: '',
  land_number: '',
  building_area: 1000,
  property_area: 800,
  rentable_space: 800,
  self_used_area: 0,
  building_images: '',
  building_features: [],
  building_introduction: '',
  room_number: 50
})

// 楼层管理相关数据
const floorList = ref([])
const floorDialogVisible = ref(false)
const roomManagementDialogVisible = ref(false)

const roomFilters = reactive({
  building: '',
  floor: ''
})

// 计算属性
const currentCampus = computed(() => {
  return campuses.value.find(c => c.id === selectedCampus.value)
})

const statsItems = computed(() => {
  if (!currentCampus.value) return []

  return [
    { label: '总租赁面积', value: `${currentCampus.value.totalArea.toLocaleString()}㎡` },
    { label: '已租面积', value: `${currentCampus.value.rentedArea.toLocaleString()}㎡` },
    { label: '使用率', value: `${currentCampus.value.usageRate}%` },
    { label: '待租面积', value: `${currentCampus.value.availableArea.toLocaleString()}㎡` }
  ]
})

const filteredData = computed(() => {
  return tableData.value.filter(item => {
    // 原有的筛选条件
    const roomNumberMatch = !filters.roomNumber || (item.roomNumber && item.roomNumber.includes(filters.roomNumber))
    const buildingMatch = !filters.building.length || (item.buildingName && filters.building.includes(item.buildingName))
    // 新增面积范围筛选
    const areaMatch = !filters.areaRange.length || filters.areaRange.some(range => {
      const area = item.area || 0
      switch (range) {
        case '0-100':
          return area < 100
        case '100-200':
          return area >= 100 && area < 200
        case '200-300':
          return area >= 200 && area < 300
        case '300-500':
          return area >= 300 && area < 500
        case '500-1000':
          return area >= 500 && area < 1000
        case '1000+':
          return area >= 1000
        default:
          return true
      }
    })

    return roomNumberMatch  && buildingMatch && areaMatch
  })
})

const buildingCount = computed(() => {
  return new Set(tableData.value.map(item => item.buildingName)).size
})

const roomCount = computed(() => {
  return tableData.value.length
})


const currentCampusBuildings = computed(() => {
  return buildingList.value.filter(b =>
      b && (b.parkId === selectedCampus.value || b.park_id === selectedCampus.value)
  )
})

const handleRemove = () => {
  currentBuilding.imageUrl = ''
}

const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url
  dialogImageVisible.value = true
}

const handleUploadSuccess = (response, file, fileList) => {
  // 实际项目中这里应该获取服务器返回的图片URL
  currentBuilding.imageUrl = URL.createObjectURL(file.raw)
}

// API调用方法
const fetchParks = async () => {
  try {
    loading.value = true
    const response = await axios.get(`${API_BASE}/api/client/parks`)
    console.log('获取园区数据：',response.data)
    campuses.value = response.data.map(campus => ({
          id:campus.parkId,
          park_id: campus.parkId,
          park_name: campus.parkName,
          address: campus.address,
          description: campus.description,
          totalArea: campus.totalArea || 0,
          rentedArea: campus.rentedArea || 0,
          availableArea: campus.availableArea || 0,
          usageRate: campus.usageRate || 0
    }))

    console.log('转换后的园区数据:', campuses.value)

    if (campuses.value.length > 0 && !selectedCampus.value) {
      selectedCampus.value = campuses.value[0].park_id
      console.log('设置默认园区ID:', selectedCampus.value)
    }
  } catch (error) {
    console.error('获取园区数据失败:', error)
    ElMessage.error('获取园区数据失败')
  }finally{
    loading.value = false
  }
}

const fetchRooms = async () => {
  try {
    tableLoading.value = true
    const params = {
      parkId: selectedCampus.value,
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize
    }

    // 添加筛选条件
    if (filters.roomNumber) {
      params.roomNumber = filters.roomNumber
    }
    if (filters.areaRange.length > 0) {
      params.areaRange = filters.areaRange
    }

    // 楼宇筛选处理
    if (filters.building.length > 0) {
      const selectedBuildingIds = buildingList.value
          .filter(b => filters.building.includes(b.name))
          .map(b => b.id)
      if (selectedBuildingIds.length === 10) {
        params.buildingId = selectedBuildingIds[0].id
      }
    }

    console.log('厂房查询参数:', params)
    const response = await axios.get(`${API_BASE}/api/client/parks/rooms`, { params })
    console.log('厂房列表完整响应:', response.data)

    // 修正字段映射
    const rooms = (response.data.list || response.data.data || response.data || []).map(room => {
      console.log('单个厂房原始数据:', room)
      return {
        id: room.id,
        parkId: room.parkId,
        buildingId: room.buildingId,
        buildingName: room.building_name || room.name || getBuildingNameById(room.buildingId) || '未知楼宇', // 使用 room.name
        floorName: room.floor || '未知楼层',
        roomNumber: room.roomNumber,
        type: room.type || '办公室',
        area: room.area || 0,
        rentPrice: room.rentPrice,
        propertyPrice: room.propertyPrice,
        rentBase: room.rentPrice ? `${room.rentPrice}元/㎡·天` : '待定',
        propertyBase: room.propertyPrice ? `${room.propertyPrice}元/㎡·月` : '待定',
        status: room.status || '待租',
        remark: room.remark || ''
      }
    })

    tableData.value = rooms
    pagination.total = response.data.total || 0

    console.log('处理后的厂房数据:', tableData.value)
  } catch (error) {
    console.error('获取厂房列表失败:', error)
    ElMessage.error('获取厂房列表失败: ' + (error.response?.data?.message || error.message))
    tableData.value = []
    pagination.total = 0
  } finally {
    tableLoading.value = false
  }
}

// 添加辅助方法：根据楼宇ID获取楼宇名称
const getBuildingNameById = (buildingId) => {
  const building = buildingList.value.find(b => b.id === buildingId)
  return building ? building.name : null
}

const fetchBuildings = async () => {
  if (!selectedCampus.value) {
    ElMessage.warning('请先选择园区')
    return
  }

  try {
    loading.value = true
    const response = await axios.get(`${API_BASE}/api/client/parks/buildings`, {
      params: { campusId: selectedCampus.value }
    })
    console.log('楼宇数据:', response.data)

    // 正确映射字段，确保包含所有必要的字段
    buildingList.value = response.data.map(building => ({
      id: building.id,
      parkId: building.parkId,
      name: building.name,
      buildingNumber: building.buildingNumber,
      groundFloorPlan: building.groundFloorPlan,
      undergroundFloorPlan: building.undergroundFloorPlan,
      buildingAddress: building.buildingAddress,
      property_region: building.propertyRegion,
      property_region_text: getPropertyTypeLabel(building.propertyRegion),
      realEstateNumber: building.realEstateNumber,
      propertyRightsNumber: building.propertyRightsNumber,
      landNumber: building.landNumber,
      buildingArea: building.buildingArea,
      propertyArea: building.propertyArea,
      rentableSpace: building.rentableSpace,
      selfUsedArea: building.selfUsedArea,
      buildingImages: building.buildingImages,
      buildingFeatures: building.buildingFeatures,
      buildingIntroduction: building.buildingIntroduction,
      roomNumber: building.roomNumber,
      address: building.buildingAddress,
      roomCount: building.roomNumber || 0,
      rentableArea: building.rentableSpace || 0
    }))

    console.log('转换后的楼宇数据:', buildingList.value)
  } catch (error) {
    console.error('获取楼宇列表失败:', error)
    ElMessage.error('获取楼宇列表失败')
  } finally {
    loading.value = false
  }
}

const fetchFloors = async () => {
  try {
    const params = {
      campusId: selectedCampus.value // 使用正确的参数名
    }

    const response = await axios.get(`${API_BASE}/api/client/parks/floors`, { params })
    console.log('原始楼层数据:', response.data)

    // 修正字段映射
    floorList.value = (response.data || []).map(floor => {
      const floorObj = {
        id: floor.id,
        campusId: floor.campusId,
        buildingId: floor.buildingId,
        floorName: floor.floorName, // 使用正确的字段名
        floorCode: floor.floorCode, // 使用正确的字段名
        floorHeight: floor.floorHeight, // 使用正确的字段名
        createTime: floor.createTime,
        updateTime: floor.updateTime
      }

      // 查找对应的园区信息
      const campus = campuses.value.find(c =>
          c.park_id === floor.campusId || c.id === floor.campusId
      )
      if (campus) {
        floorObj.campusName = campus.park_name || '未知园区'
      } else {
        floorObj.campusName = '未知园区'
      }

      // 查找对应的楼宇信息
      const building = buildingList.value.find(b => b.id === floor.buildingId)
      if (building) {
        floorObj.buildingName = building.name || '未知楼宇'
      } else {
        floorObj.buildingName = '未知楼宇'
      }

      return floorObj
    })

    console.log('转换后的楼层数据:', floorList.value)
  } catch (error) {
    console.error('获取楼层列表失败:', error)
    ElMessage.error('获取楼层列表失败')
  }
}

const manageFloors = async () => {
  try {
    loading.value = true

    // 确保园区数据已加载
    if (campuses.value.length === 0) {
      await fetchParks()
    }

    // 确保楼宇数据已加载
    if (buildingList.value.length === 0 && selectedCampus.value) {
      await fetchBuildings()
    }

    // 获取楼层数据
    await fetchFloors()

    floorDialogVisible.value = true
  } catch (error) {
    console.error('打开楼层信息失败:', error)
    ElMessage.error('打开楼层信息失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

const viewRoomDetail = async (row) => {
  try {
    // 直接使用当前行的数据，或者从API获取完整详情
    currentRoom.value = {
      ...row,
      name: row.buildingName, // 确保楼宇名称正确
      room_number: row.roomNumber,
      floor: row.floorName,
      area: row.area,
      status: row.status,
      rent_price: row.rentPrice,
      property_price: row.propertyPrice,
      type: row.type
    }
    roomDetailDialogVisible.value = true
  } catch (error) {
    console.error('查看厂房详情失败:', error)
    ElMessage.error('查看厂房详情失败')
  }
}

const manageBuildings = async () => {
  try {
    const response = await axios.get(`${API_BASE}/api/client/parks/buildings`, {
      params: { campusId: selectedCampus.value }
    })

    // 正确映射字段
    buildingList.value = response.data.map(building => ({
      id: building.id,
      name: building.name,
      buildingArea: building.buildingArea || 0,
      rentableArea: building.rentableSpace || 0,
      roomCount: building.roomNumber || 0,
      address: building.buildingAddress || '无地址信息'
    }))

    if (buildingList.value.length === 0) {
      await fetchBuildings()
    }

    buildingDialogVisible.value = true
  } catch (error) {
    console.error('获取楼宇列表失败:', error)
    ElMessage.error('获取楼宇列表失败')
  }
}

// 查看楼宇详情
const viewBuildingDetail = async (building) => {
  try {
    console.log('查看楼宇详情，ID:', building.id)

    // 重置当前楼宇数据
    resetBuildingForm()

    // 获取楼宇详情数据
    const response = await axios.get(`${API_BASE}/api/client/parks/buildings/${building.id}`)
    console.log('楼宇详情响应:', response.data)

    // 将响应数据映射到 currentBuilding
    const buildingData = response.data
    Object.assign(currentBuilding, {
      id: buildingData.id,
      park_id: buildingData.parkId,
      name: buildingData.name,
      building_number: buildingData.buildingNumber,
      ground_floor_plan: buildingData.groundFloorPlan || 0,
      underground_floor_plan: buildingData.undergroundFloorPlan || 0,
      building_address: buildingData.buildingAddress,
      property_region: buildingData.propertyRegion,
      real_estate_number: buildingData.realEstateNumber,
      property_rights_number: buildingData.propertyRightsNumber,
      land_number: buildingData.landNumber,
      building_area: buildingData.buildingArea || 0,
      property_area: buildingData.propertyArea || 0,
      rentable_space: buildingData.rentableSpace || 0,
      self_used_area: buildingData.selfUsedArea || 0,
      building_images: buildingData.buildingImages,
      building_introduction: buildingData.buildingIntroduction,
      room_number: buildingData.roomNumber || 0
    })

    // 处理设施服务字段
    if (buildingData.buildingFeatures) {
      if (typeof buildingData.buildingFeatures === 'string') {
        currentBuilding.building_features = buildingData.buildingFeatures.split(',').filter(item => item.trim() !== '')
      } else if (Array.isArray(buildingData.buildingFeatures)) {
        currentBuilding.building_features = buildingData.buildingFeatures
      } else {
        currentBuilding.building_features = []
      }
    } else {
      currentBuilding.building_features = []
    }

    // 处理图片
    if (buildingData.buildingImages) {
      fileList.value = [{
        name: '楼宇图片',
        url: buildingData.buildingImages
      }]
    } else {
      fileList.value = []
    }

    // 打开详情对话框
    viewDialogVisible.value = true
    viewMode.value = true

  } catch (error) {
    console.error('获取楼宇详情失败:', error)
    ElMessage.error('获取楼宇详情失败: ' + (error.response?.data?.message || error.message))
  }
}

const updateBuildingOptions = () => {
  buildingOptions.value = buildingList.value.map(b => ({
    value: b.name,
    label: b.name
  }))
}

const fetchPropertyTypes = async () => {
  try {
    const response = await axios.get(`${API_BASE}/api/property-types`)
    propertyTypes.value = response.data
    console.log('产权类型数据:', propertyTypes.value)
  } catch (error) {
    console.error('获取产权类型失败:', error)
    // 如果接口不可用，使用默认值
    propertyTypes.value = [
      { value: 'STATE_OWNED', label: '国有' },
      { value: 'COLLECTIVE', label: '集体' },
      { value: 'PRIVATE', label: '私有' },
      { value: 'FOREIGN', label: '外资' },
      { value: 'JOINT_VENTURE', label: '合资' }
    ]
  }
}

const getPropertyTypeLabel = (value) => {
  if (!value) return ''
  const found = propertyTypes.value.find(item => item.value === value)
  return found ? found.label : value
}

const handleBuildingDialogClose = () => {
  updateBuildingOptions()
}

const updateCampusInfo = async () => {
  // 获取园区统计信息
  const stats = await fetchParkStats(selectedCampus.value)
  if (stats) {
    // 更新当前园区的统计信息
    const current = campuses.value.find(c => c.park_id === selectedCampus.value)
    if (current) {
      Object.assign(current, stats)
    }
  }

  await fetchBuildings()
  await fetchRooms()
  updateBuildingOptions()
}

const fetchParkStats = async (parkId) => {
  try {
    const response = await axios.get(`${API_BASE}/api/client/parks/stats`, {
      params: { parkId }
    })
    return response.data
  } catch (error) {
    console.error('获取园区统计信息失败:', error)
    return null
  }
}


const filteredRoomData = computed(() => {
  return tableData.value.filter(item => {
    const buildingMatch = !roomFilters.building ||
        item.buildingName === roomFilters.building
    const floorMatch = !roomFilters.floor ||
        item.floorName === roomFilters.floor
    return buildingMatch && floorMatch
  })
})

const getAvailableFloors = (building) => {
  if (!building) return []
  const floors = [...new Set(
      tableData.value
          .filter(item => item.buildingName === building)
          .map(item => item.floorName)
  )]
  return floors.sort()
}

const manageRooms = async () => {
  try {
    loadingRooms.value = true
    roomFilters.building = ''
    roomFilters.floor = ''

    // 重新获取房间数据
    await fetchRooms()

    roomManagementDialogVisible.value = true
  } catch (error) {
    console.error('打开房间信息失败:', error)
    ElMessage.error('打开房间信息失败')
  } finally {
    loadingRooms.value = false
  }
}

const filterRooms = () => {
  if (roomFilters.building && !getAvailableFloors(roomFilters.building).includes(roomFilters.floor)) {
    roomFilters.floor = ''
  }
}

// 分页处理
const handleSizeChange = (newSize) => {
  pagination.pageSize = newSize
  pagination.currentPage = 1
  fetchRooms()
}

const handleCurrentChange = (newPage) => {
  pagination.currentPage = newPage
  fetchRooms()
}

const roomData = ref([])

const resetRoomManagementForm = () => {
  roomFilters.building = ''
  roomFilters.floor = ''
}

const resetBuildingForm = () => {
  viewMode.value = false
  Object.assign(currentBuilding, {
    id: null,
    park_id: selectedCampus.value,
    name: '',
    building_number: '',
    ground_floor_plan: 0,
    underground_floor_plan: 0,
    building_address: '',
    property_region: '',
    real_estate_number: '',
    property_rights_number: '',
    land_number: '',
    building_area: 1000,
    property_area: 800,
    rentable_space: 800,
    self_used_area: 0,
    building_images: '',
    building_features: [],
    building_introduction: '',
    room_number: 50
  })
  fileList.value = []
}
const propertyRegionText = computed(() => {
  return getPropertyTypeLabel(currentBuilding.property_region)
})

onMounted(() => {
  fetchParks().then(() => {
    // 确保先获取楼宇数据，再获取房间数据
    fetchBuildings().then(() => {
      updateBuildingOptions()
      fetchRooms()
    })
  })
  fetchPropertyTypes()
})

// 监听筛选条件变化
watch(() => filters.roomNumber, () => {
  pagination.currentPage = 1
  fetchRooms()
})

watch(() => filters.building, () => {
  pagination.currentPage = 1
  fetchRooms()
})
</script>

<style scoped>
/* 添加园区图片背景 */
.campus-avatar[data-campus="1"] {
  background-image: url('https://img95.699pic.com/photo/60022/4177.jpg_wh860.jpg');
  background-size: cover;
  background-position: center;
}

.campus-avatar[data-campus="2"] {
  background-image: url('https://img95.699pic.com/photo/50082/8358.jpg_wh860.jpg');
  background-size: cover;
  background-position: center;
}

/* 其他样式保持不变 */
.empty-tip {
  padding: 40px 0;
  text-align: center;
}

:deep(.el-descriptions) {
  margin: 10px 0;
}

:deep(.el-descriptions__label) {
  width: 120px;
  font-weight: bold;
  background-color: #f5f7fa;
}

:deep(.el-descriptions__content) {
  padding-left: 20px;
}
.action-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
}
.footer-buttons {
  display: flex;
  justify-content: flex-end; /* 靠右对齐 */
  gap: 10px; /* 按钮间距 */
}

.el-checkbox-group {
  display: flex;
  flex-wrap: wrap;
}
.el-checkbox {
  width: 120px;
  margin-right: 10px;
}

.dialog-footer {
  padding-top: 20px;
  text-align: right;
}
.room-management {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  background: #f5f7fa;
}

/* 上模块样式 */
.top-section .el-card {
  border-radius: 8px;
}

.campus-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  min-height: 200px;
  position: relative;
}

.left-panel {
  display: flex;
  gap: 30px;
  width: 75%;
}

.campus-avatar {
  flex-shrink: 0;
  box-shadow: 0 4px 16px rgba(0,0,0,0.1);
  height: 160px;
  width: 160px;
}

.campus-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.name-area {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 25px;
}

.campus-name {
  margin: 0;
  font-size: 24px;
  color: #303133;
  font-weight: 600;
}

.campus-switcher {
  width: 180px;
}

.campus-switcher ::v-deep .el-input__inner {
  height: 36px;
  line-height: 36px;
  font-size: 14px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.stat-item {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 6px;
  border-left: 4px solid var(--el-color-primary);
}

.stat-label {
  color: #909399;
  font-size: 14px;
  margin-bottom: 6px;
}

.stat-value {
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.manage-btn {
  position: absolute;
  top: 20px;
  right: 20px;
  padding: 10px 20px;
  font-size: 14px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  transition: all 0.3s ease;
}

.manage-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

/* 中模块样式 - 筛选框布局调整 */
.filter-card .el-card__body {
  padding: 20px;
}

.filter-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.filter-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.filter-label {
  min-width: 60px;
  color: #606266;
  font-size: 14px;
  white-space: nowrap;
}

.filter-input,
.filter-select {
  flex: 1;
  max-width: 400px;
}

/* 楼宇筛选框特定样式 */
.building-select {
  max-width: 400px !important; /* 与房间号筛选框保持一致 */
}

/* 下模块样式 */
.table-card .el-card__body {
  padding: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.summary-text {
  color: #606266;
  font-size: 14px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 10px;
}

.data-table {
  margin-top: 16px;
}

/* 分页样式 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .left-panel {
    width: 85%;
  }

  .campus-name {
    font-size: 20px;
  }

  .filter-row {
    grid-template-columns: 1fr;
  }
}

.action-btn {
  width: 80px;
  padding: 7px 10px;
}

/* 确保按钮图标和文字间距一致 */
.action-btn :deep(.el-icon) {
  margin-right: 4px;
}

@media (max-width: 768px) {
  .room-management {
    padding: 12px;
    gap: 15px;
  }

  .campus-header {
    flex-direction: column;
    min-height: auto;
  }

  .left-panel {
    width: 100%;
    flex-direction: column;
  }

  .campus-avatar {
    align-self: center;
  }

  .name-area {
    flex-direction: column;
    align-items: flex-start;
  }

  .manage-btn {
    position: static;
    width: 100%;
    margin-top: 15px;
  }

  .stats-grid {
    grid-template-columns: 1fr;
  }

  .filter-item {
    flex-direction: column;
    align-items: flex-start;
  }

  .filter-input,
  .filter-select {
    width: 100%;
    max-width: none;
  }

  .table-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .header-right {
    width: 100%;
    justify-content: space-between;
  }
  .action-buttons {
    flex-direction: column;
    align-items: center;
    gap: 5px;
  }

  .action-btn {
    width: 100%;
    margin: 2px 0;
  }
}

.picture-preview {
  z-index: 10002 !important;
}

:deep(.picture-preview) {
  z-index: 10002 !important;
}


/* 确保图片预览遮罩层在正确层级 */
.el-overlay .picture-preview {
  z-index: 10002 !important;
}

/* 操作栏文字样式 */
.action-text {
  cursor: pointer;
  margin: 0 5px;
}

.action-text.info {
  color: #909399;
}

.action-text.primary {
  color: var(--el-color-primary);
}

.action-text.danger {
  color: var(--el-color-danger);
}

.dialog-header {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
}

.add-floor-btn {
  margin-bottom: 10px;
}
</style>

<style>
/* 全局样式 - 解决对话框层级问题 */
.building-manage-dialog {
  position: relative;
  z-index: 2000;
}

.delete-confirm-box {
  position: relative;
  z-index: 10000 !important;
}

/* 确保遮罩层正确显示 */
.el-overlay {
  z-index: 1000 !important;
}

.el-overlay:has(.delete-confirm-box) {
  z-index: 9999 !important;
}
</style>